import { constantRoutes, afterRoutes } from '@/router/index.js';

const modulesFiles = require.context('@/router/asyncRoutes/', true, /\.js$/);
const asyncRoutes = modulesFiles.keys().reduce((modules, modulePath) => {
  const value = modulesFiles(modulePath);
  modules.push(value.default);
  return modules;
}, []);

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];

  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });

  return res;
}

function generateRoutesArray(accessedRoutes) {
  const res = [];

  function handler(routes, parentRouter = '') {
    for (const val of routes) {
      if (val.children && val.children.length > 0) {
        parentRouter += val.path;
        handler(val.children, parentRouter);
      } else {
        res.push(parentRouter);
        parentRouter = '';
      }
    }
  }

  handler(accessedRoutes);
  // console.log(res);
}

export default {
  namespaced: true,
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = [...constantRoutes, ...routes, ...afterRoutes];
    }
  },
  actions: {
    generateRoutes({ commit }, roles) {
      return new Promise(resolve => {
        const reRolesName = [];
        for (const val of roles) {
          reRolesName.push(val.role_name);
        }
        let accessedRoutes;
        if (reRolesName.includes('九条米法')) {
          accessedRoutes = asyncRoutes || [];
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, reRolesName);
        }
        commit('SET_ROUTES', accessedRoutes);
        resolve(accessedRoutes.concat(afterRoutes));
        // generateRoutesArray(accessedRoutes);
      });
    }
  }
};
